import time

from fastapi import FastAPI, Request, Depends, Header, HTTPException
from fastapi.staticfiles import StaticFiles
from tortoise.contrib.fastapi import register_tortoise

from app.allsubdb import wanfangqk, chaoxingqk, jss_wf, gsdata, paper_jingjiribao, paper_xuexishibao, \
    paper_jiefangjunbao, paper_guangmingribao, paper_renminribao_guonei, paper_renminribao_haiwai, cnkijournal, \
    paper_beijingribao,test_chaoxingjournal
from app.routers import items, users, mongos
# from app.sql_app.database import create_table
from app.sql_app.mmongodb import connect_to_mongo, close_mongo_connection, MongoDBClient
from settings import Settings, get_settings

# uvicorn main:app --reload --host=0.0.0.0 --port=8000

app = FastAPI(title="caiji project", openapi_url=f"/api/v1/openapi.json")
app.mount("/static", StaticFiles(directory="static"), name="static")

register_tortoise(
    app,
    config={
        "connections": {
            "first": "mysql://root:vipdatacenter@192.168.31.207:3306/collection_server?charset=utf8mb4",
            "second": "mysql://root:vipdatacenter@192.168.31.209:3306/jss_wf_patent?charset=utf8mb4"
        },
        "apps": {
            "db207": {"models": ["app.allsubdb.tools.models"], "default_connection": "first"},
            "db209": {"models": ["app.allsubdb.jss_wf.models"], "default_connection": "second"}
        },
    },
    # db_url = "mysql://root:vipdatacenter@192.168.31.207:3306/collection_server?charset=utf8mb4",
    # modules={"models": ["models"]},
    generate_schemas=True,  # 如果为True，则立即生成架构。仅对开发环境有用或SQLite``：内存：``数据库
    add_exception_handlers=True,  # 添加一些自动异常处理程序，则为True。这不建议用于生产系统，因为它可能泄漏数据。
)


@app.on_event("startup")
async def startup():
    """
    在所有 startup 事件处理程序完成 之前，您的应用程序将不会开始接收请求 。
    :return:
    """
    from app.sql_app.database import database
    # create_table()
    await database.connect()
    MongoDBClient.db30_1 = await connect_to_mongo("mongodb://192.168.31.30:32417", "htmljson")
    from mongoengine import connect
    connect('collection', host='192.168.31.166', port=27017, username='cjrw', password='vipdatacenter', alias='default')
    connect('collection', host='192.168.31.168', port=27017, alias='db68')
    connect('htmljson', host='192.168.31.30', port=32417, alias='db30_1')
    connect('bs', host='192.168.31.168', port=27017, alias='db68bs')
    connect('hy', host='192.168.31.168', port=27017, alias='db68hy')
    connect('wanfangqk', host='192.168.31.168', port=27017, alias='db68wfqk')
    connect('htmljson', host='192.168.31.30', port=32417, alias='db30cxqk')
    connect('htmljson', host='192.168.31.206', port=32920, username='cjrw', password='vipdatacenter', alias='db243cxqk')


@app.on_event("shutdown")
async def shutdown():
    """
    要添加应在应用程序关闭时运行的功能，请使用事件声明它 "shutdown"
    :return:
    """
    from app.sql_app.database import database
    await database.disconnect()
    await close_mongo_connection(MongoDBClient.db30_1)
    from mongoengine import disconnect
    disconnect(alias='db68')
    disconnect(alias='default')
    disconnect(alias='db68bs')
    disconnect(alias='db68hy')
    disconnect(alias='db68wfqk')
    disconnect(alias='db68cxqk')


@app.get("/info")
async def info(settings: Settings = Depends(get_settings)):
    return {
        "app_name": settings.app_name,
        "admin_email": settings.SQLALCHEMY_DATABASE_URI,
    }


@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    return response


async def get_token_header(x_token: str = Header(...)):
    if x_token != "fake-super-secret-token":
        raise HTTPException(status_code=400, detail="X-Token header invalid")


app.include_router(users.router, prefix="/user", )
app.include_router(mongos.router, prefix="/mongo", )
app.include_router(wanfangqk.router, prefix="/wanfangqk", tags=["wanfangqk"])
app.include_router(chaoxingqk.cxqk_save_routers, prefix="/chaoxingqk", tags=["chaoxingqk"])
app.include_router(chaoxingqk.cxqk_down_routers, prefix="/chaoxingqk_down_detail", tags=["chaoxingqk_down_detail"])

app.include_router(jss_wf.router, prefix="/jss_wf", tags=["jss_wf"])
app.include_router(wanfangqk.wfqk_down_routers, prefix="/wanfangqk_down", tags=["wanfangqk_down"])
app.include_router(cnkijournal.cnkiqk_down_routers, prefix="/cnkiqk_down", tags=["cnkiqk_down"])
app.include_router(gsdata.gsdata_router, prefix="/gsdata", tags=["gsdata"])
app.include_router(paper_jingjiribao.paper_jingjiribao_router, prefix="/paper_jingjiribao", tags=["paper_jingjiribao"])
app.include_router(paper_xuexishibao.paper_xuexishibao_router, prefix="/paper_xuexishibao", tags=["paper_xuexishibao"])
app.include_router(paper_beijingribao.paper_beijingribao_router, prefix="/paper_beijingribao", tags=["paper_beijingribao"])
app.include_router(paper_jiefangjunbao.paper_jiefangjunbao_router, prefix="/paper_jiefangjunbao",
                   tags=["paper_jiefangjunbao"])
app.include_router(paper_guangmingribao.paper_guangmingribao_router, prefix="/paper_guangmingribao",
                   tags=["paper_guangmingribao"])
app.include_router(paper_renminribao_guonei.paper_renminribao_guonei_router, prefix="/paper_renminribao_guonei",
                   tags=["paper_renminribao_guonei"])
app.include_router(paper_renminribao_haiwai.paper_renminribao_haiwai_router, prefix="/paper_renminribao_haiwai",
                   tags=["paper_renminribao_haiwai"])
# app.include_router(test_chaoxingjournal.test_chaoxingjournal_router, prefix="/test_chaoxingjournal",
#                    tags=["test_chaoxingjournal"])
app.include_router(
    items.router,
    prefix="/items",
    tags=["items"],
    dependencies=[Depends(get_token_header)],
    responses={404: {"description": "Not found"}},
)
